package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.help.PaasExcelExportHelp;
import com.xbongbong.paas.pojo.dto.ImportPerformanceDTO;
import com.xbongbong.paas.pojo.dto.PerformanceDownloadDTO;
import com.xbongbong.paas.pojo.vo.ExcelTemplateVO;
import com.xbongbong.paas.pojo.vo.ImportPerformanceVO;
import com.xbongbong.paas.service.PaasExcelService;
import com.xbongbong.paas.service.PerformanceImportService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.OutputStream;
import java.util.Objects;

/**
 * 业绩目标导入导出相关接口
 *
 * @author wufeng
 * @date 2018/9/21 10:57
 */
@RestController
@RequestMapping(value = XbbProConstant.API_ROOT_PREFIX + "/file/excel")
public class PerformanceImportController {

    @Resource
    private PerformanceImportService performanceImportService;
    @Resource
    private PaasExcelService paasExcelService;

    /**
     * 业绩目标导入模板下载
     */
    @RequestMapping(value = "/template/download/performance")
    public String templateDownLoadPerformance(@RequestBody @Valid PerformanceDownloadDTO performanceDownloadDTO, BindingResult br, HttpServletResponse httpServletResponse) throws Exception {
        XbbResponse<ExcelTemplateVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            ExcelTemplateVO excelTemplateVO = new ExcelTemplateVO();
            try {
                excelTemplateVO = performanceImportService.getPerformanceTemplate(performanceDownloadDTO);
                httpServletResponse.reset();
                httpServletResponse.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(excelTemplateVO.getName(), "utf-8"));
                OutputStream toClient = httpServletResponse.getOutputStream();
                httpServletResponse.setContentType("application/vnd.ms-excel;charset=utf-8");
                excelTemplateVO.getWorkbook().write(toClient);
                toClient.flush();
                toClient.close();
                return null;
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            } finally {
                PaasExcelExportHelp.closeWorkBookException(excelTemplateVO.getWorkbook());
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 业绩目标导入
     */
    @RequestMapping("/performance/importExcel")
    public String importPerformance(@ModelAttribute @Valid ImportPerformanceDTO importPerformanceDTO, BindingResult br) throws Exception {
        XbbResponse<ImportPerformanceVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                UserVO userVo = paasExcelService.getUserVo(importPerformanceDTO.getCorpid(), importPerformanceDTO.getUserId());
                importPerformanceDTO.setLoginUser(userVo);
                ImportPerformanceVO importPerformanceVO = performanceImportService.importPerformanceData(importPerformanceDTO);
                response = new XbbResponse<>(importPerformanceVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            }
        }
        return JSON.toJSONString(response);
    }

    /**
     * 业绩目标错误数据excel下载
     */
    @RequestMapping(value = "/error/download/performance", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String errorDownloadPerformance(@RequestBody @Valid BaseDTO baseDTO, BindingResult br, HttpServletResponse httpServletResponse) {
        XbbResponse<ExcelTemplateVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            Workbook errorExcel = null;
            try {
                String name = I18nMessageUtil.getMessage(I18nStringConstant.PERFORMANCE_INDICATOR_IMPORT_ERROR_DATA_EXCEL);
                errorExcel = performanceImportService.performanceErrorDownLoad(baseDTO);
                httpServletResponse.reset();
                httpServletResponse.addHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(name, "utf-8"));
                OutputStream toClient = httpServletResponse.getOutputStream();
                httpServletResponse.setContentType("application/vnd.ms-excel;charset=utf-8");
                errorExcel.write(toClient);
                toClient.flush();
                toClient.close();
                return null;
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            } catch (Exception unHandledException) {
                response = new XbbResponse<>(new XbbException(SystemErrorCodeEnum.API_ERROR_100001, unHandledException.getMessage()));
            } finally {
                PaasExcelExportHelp.closeWorkBookException(errorExcel);
            }
        }
        return JSON.toJSONString(response);
    }
}
